const express = require('express')
const router = express.Router()
const { getQQAvatar, urlToFile } = require('../utils/meme.js')
const { FormData } = require('node-fetch')
const axios = require('axios')

// const memeUrl = 'http://localhost:2233'
const memeUrl = 'https://meme.diona.site'

router.get('/', async function (req, res, next) {
    const { qq, key, image, text } = req.query
    try {
        const qqs = qq ? qq.split(',') : []
        const texts = text ? text.split(',') : []
        const images = image ? image.split(',') : []

        const qqImages = qqs.map(qq => getQQAvatar(qq))
        const allImages = [...qqImages, ...images]
        const files = await Promise.all(allImages.map(urlToFile))

        const formData = new FormData()
        files.forEach(f => formData.append('images', f))
        texts.forEach(t => formData.append('texts', t))

        const response = await axios({
            url: `${memeUrl}/memes/${key}/`,
            method: 'post',
            data: formData,
            responseType: 'stream'
        })

        res.setHeader('Access-Control-Allow-Origin', '*')
        res.setHeader('Content-Type', response.headers['content-type'] || 'image/jpeg')

        response.data.pipe(res)
    } catch (err) {
        res.status(500).send(err)
    }
})

module.exports = router
